package cc.dowell.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cc.dowell.mapper.FruitMapper;
import cc.dowell.mapper.UserMapper;
import cc.dowell.pojo.Fruit;
import cc.dowell.pojo.User;
import cc.dowell.service.FruitService;
import cc.dowell.vo.FruitVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

@Service
public class FruitServiceImpl extends ServiceImpl<FruitMapper, Fruit> implements FruitService {

    @Autowired
    private FruitMapper fruitMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<FruitVo> selectFruitPage(Page<Fruit> page,String fruitName) {
        //查询fruit的列表数据
        LambdaQueryWrapper<Fruit> lqw = new LambdaQueryWrapper<>();
        //按照修改时间排序（晚-->早）
        lqw.orderByDesc(Fruit::getUpdateTime);
        //查询条件
        lqw.like(!fruitName.isEmpty(),Fruit::getName,fruitName);
        IPage<Fruit> fruitPage = fruitMapper.selectPage(page, lqw);

        //初始化Vo
        IPage<FruitVo> fruitVoPage = new Page<>();
        //mp提供了convert方法,将数据重新封装
        // IPage<FruitVo> fruitVoPage = fruitPage.convert(FruitVo::new);
        if(fruitPage.getRecords().size()>0){
            //提取createUser的集合，进行第二次查询
            Set<Long> userSet = fruitPage.getRecords().stream()
                    .map(Fruit::getCreateUserId).collect(Collectors.toSet());
            //根据userSet查询nickname
            List<User> userList = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getId, userSet));
            // 构造Map映射关系，方便匹配userId与nickname
            Map<Long,String> userMap = userList.stream().collect(toMap(User::getId, User::getNickname));
            // 将查询补充的信息添加到Vo中
            fruitVoPage = fruitPage.convert(u -> {
                FruitVo vo = new FruitVo();
                String nickname = userMap.get(u.getCreateUserId());
                vo.setNickname(nickname);
                BeanUtils.copyProperties(u, vo);
                return vo;
            });

        }

        return fruitVoPage;
    }

    @Override
    public Fruit selectFruitByCode(String varietyCode) {
        LambdaQueryWrapper<Fruit> lqw = new LambdaQueryWrapper<>();
        lqw.eq(!varietyCode.isEmpty(),Fruit::getVariety,varietyCode);
        Fruit fruit = fruitMapper.selectOne(lqw);
        return fruit;

    }
}
